from PyQt5.QtGui import QIcon, QFont, QPalette, QColor, QCloseEvent, QPixmap
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QPushButton, QLabel,
                             QLineEdit, QHBoxLayout, QMessageBox, QFrame, QSpacerItem, QSizePolicy, QListWidget,
                             QListWidgetItem, QRadioButton, QScrollArea)
import requests
import threading
import re
from PyQt5.QtCore import Qt, QVariant, QSize
import base64


class AdminMenu(QWidget):
    def __init__(self, parent=None):
        super().__init__()
        self.setWindowTitle('管理员菜单')
        self.parent = parent
        self.clear_layout = self.parent.clear_layout
        self.create_scroll = self.parent.create_scroll
        self.resize(800, 1100)  # 设置最小窗口大小

        # 设置窗口图标
        try:
            icon = QIcon('../static/image/管理员.png')
            self.setWindowIcon(icon)
        except:
            pass

        # 设置全局字体
        font = QFont()
        font.setFamily("Microsoft YaHei")
        font.setPointSize(10)
        self.setFont(font)

        # 设置背景颜色
        palette = QPalette()
        palette.setColor(QPalette.Window, QColor(245, 245, 245))
        self.setPalette(palette)

        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(30, 40, 30, 40)  # 外边框
        main_layout.setSpacing(20)  # 控件间距
        self.initUI(main_layout)

    def initUI(self, main_layout):
        layout_s = QVBoxLayout()
        main_layout.addLayout(layout_s)
        # 添加标题
        title_label = QLabel("管理员操作菜单")
        title_font = QFont()
        title_font.setFamily("Microsoft YaHei")
        title_font.setPointSize(16)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet(
            "color: #2c3e50; margin-bottom: 10px; padding: 15px; background: white; border-radius: 8px; border: 1px solid #ddd;")
        layout_s.addWidget(title_label)

        # 添加分隔线
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        line.setStyleSheet("background-color: #3498db; height: 2px; margin: 10px 0;")
        layout_s.addWidget(line)

        layout1 = QHBoxLayout()
        layout_s.addLayout(layout1)
        frame = self.create_left_frame1()
        layout1.addWidget(frame)
        self.right_layout = QVBoxLayout()
        layout1.addLayout(self.right_layout)

        self.user_frame()
        self.update_account_placeholder(True)

        s_frame=QFrame()
        main_layout.addWidget(s_frame)
        s_frame.setFixedHeight(590)
        s_layout = QVBoxLayout(s_frame)
        frame = self.create_scroll(s_layout)
        frame.setStyleSheet("background: white; border-radius: 8px; border: 1px solid #ddd; padding: 15px;")
        self.x_layout = QHBoxLayout(frame)
        self.init_x_layout()

    # 左边第一个容器：
    def create_left_frame1(self):
        frame = QFrame()
        frame.setFixedSize(300,500)
        frame.setStyleSheet("background: white; border-radius: 8px; border: 1px solid #ddd;")
        layout = QVBoxLayout(frame)
        list_item = QListWidget()
        list_item.setStyleSheet("""
            QListWidget {
                border: none;
                background: transparent;
                outline: none;
            }
            QListWidget::item {
                padding: 12px 15px;
                border-bottom: 1px solid #eee;
                color: #2c3e50;
            }
            QListWidget::item:hover {
                background: #f8f9fa;
            }
            QListWidget::item:selected {
                background: #3498db;
                color: white;
            }
        """)
        layout.addWidget(list_item)
        texts = ['用户', '课程', '班级', '返回']
        for text in texts:
            item = QListWidgetItem(text)
            list_item.addItem(item)
        list_item.itemDoubleClicked.connect(self.list_double_clicked)
        return frame

    # 左边容器被双击
    def list_double_clicked(self, item):
        text = item.text()
        if text == '用户':
            self.user_frame()
            self.update_account_placeholder(True)
        elif text == '课程':
            self.course_frame()
        elif text == '班级':
            self.class_frame()
        elif text == '返回':
            self.exit()
        self.clear_layout(self.x_layout)
        self.init_x_layout()

    # 下方布局初始化
    def init_x_layout(self):
        self.clear_layout(self.x_layout)
        label = QLabel('欢迎！')
        label.setStyleSheet("color: #7f8c8d; font-size: 14px; padding: 10px;")
        self.x_layout.addWidget(label)

    # 用户管理页面
    def user_frame(self):
        self.clear_layout(self.right_layout)

        # 添加区域标题
        section_label = QLabel("用户管理")
        section_label.setStyleSheet("color: #2c3e50; font-size: 14px; font-weight: bold; margin-bottom: 15px;")
        self.right_layout.addWidget(section_label)

        type_layout = QHBoxLayout()
        self.right_layout.addLayout(type_layout)
        self.teacher_radio = QRadioButton('教师')
        self.student_radio = QRadioButton('学生')
        self.student_radio.setChecked(True)

        # 美化单选按钮
        radio_style = """
            QRadioButton {
                color: #2c3e50;
                font-weight: bold;
                padding: 8px 15px;
                background: white;
                border-radius: 4px;
                margin: 0 5px;
            }
            QRadioButton::indicator {
                width: 16px;
                height: 16px;
            }
        """
        self.teacher_radio.setStyleSheet(radio_style)
        self.student_radio.setStyleSheet(radio_style)

        self.users_layout = QVBoxLayout()
        self.right_layout.addLayout(self.users_layout)
        type_layout.addWidget(self.student_radio)
        type_layout.addWidget(self.teacher_radio)
        self.student_radio.toggled.connect(self.update_account_placeholder)

    # 课程管理页面
    def course_frame(self):
        self.clear_layout(self.right_layout)

        # 添加区域标题
        section_label = QLabel("课程管理")
        section_label.setStyleSheet("color: #2c3e50; font-size: 14px; font-weight: bold; margin-bottom: 15px;")
        self.right_layout.addWidget(section_label)

        add_layout = QHBoxLayout()
        self.right_layout.addLayout(add_layout)
        self.input_course = QLineEdit()
        add_layout.addWidget(self.input_course)
        self.input_course.setPlaceholderText("在此输入课程名")
        self.input_course.setStyleSheet("padding: 8px; border: 1px solid #ddd; border-radius: 4px; background: white;")
        add_submit = QPushButton('添加')
        add_submit.setStyleSheet("""
            QPushButton {
                background: #3498db;
                color: white;
                border: none;
                padding: 8px 15px;
                border-radius: 4px;
                margin-left: 10px;
            }
            QPushButton:hover {
                background: #2980b9;
            }
        """)
        add_layout.addWidget(add_submit)
        sco_frame = self.create_scroll(self.right_layout)
        sco_frame.setStyleSheet("background: white; border-radius: 8px; border: 1px solid #ddd; padding: 10px;")
        show_layout = QVBoxLayout(sco_frame)
        response = requests.get('http://127.0.0.1:8000/admin/get_course').json()

        courses = response['msg']
        for course in courses:
            name = course['name']
            course_layout = QHBoxLayout()
            label = QLabel(name)
            label.setStyleSheet("padding: 8px; color: #2c3e50;")
            admin_btn = QPushButton('管理')
            delete_btn = QPushButton('删除')

            # 美化按钮
            admin_btn.setStyleSheet("""
                QPushButton {
                    background: #3498db;
                    color: white;
                    border: none;
                    padding: 5px 10px;
                    border-radius: 3px;
                    margin: 0 2px;
                }
            """)
            delete_btn.setStyleSheet("""
                QPushButton {
                    background: #e74c3c;
                    color: white;
                    border: none;
                    padding: 5px 10px;
                    border-radius: 3px;
                    margin: 0 2px;
                }
            """)

            admin_btn.setProperty('name', name)
            delete_btn.setProperty('name', name)
            course_layout.addWidget(label)
            course_layout.addStretch()
            course_layout.addWidget(admin_btn)
            course_layout.addWidget(delete_btn)
            admin_btn.clicked.connect(self.admin_course_btn_clicked)
            delete_btn.clicked.connect(self.delete_course_btn_clicked)
            show_layout.addLayout(course_layout)

        add_submit.clicked.connect(self.add_course)

    # 班级管理页面
    def class_frame(self):
        self.clear_layout(self.right_layout)

        # 添加区域标题
        section_label = QLabel("班级管理")
        section_label.setStyleSheet("color: #2c3e50; font-size: 14px; font-weight: bold; margin-bottom: 15px;")
        self.right_layout.addWidget(section_label)

        add_layout = QHBoxLayout()
        self.right_layout.addLayout(add_layout)
        self.input_class = QLineEdit()
        add_layout.addWidget(self.input_class)
        self.input_class.setPlaceholderText("在此输入班级名")
        self.input_class.setStyleSheet("padding: 8px; border: 1px solid #ddd; border-radius: 4px; background: white;")
        add_submit = QPushButton('添加')
        add_submit.setStyleSheet("""
            QPushButton {
                background: #3498db;
                color: white;
                border: none;
                padding: 8px 15px;
                border-radius: 4px;
                margin-left: 10px;
            }
            QPushButton:hover {
                background: #2980b9;
            }
        """)
        add_layout.addWidget(add_submit)
        sco_frame = self.create_scroll(self.right_layout)
        sco_frame.setStyleSheet("background: white; border-radius: 8px; border: 1px solid #ddd; padding: 10px;")
        show_layout = QVBoxLayout(sco_frame)
        response = requests.get('http://127.0.0.1:8000/admin/get_class').json()
        classes = response['msg']
        for class_ in classes:
            name = class_['name']
            class_layout = QHBoxLayout()
            label = QLabel(name)
            label.setStyleSheet("padding: 8px; color: #2c3e50;")
            admin_btn = QPushButton('管理')
            delete_btn = QPushButton('删除')

            # 美化按钮
            admin_btn.setStyleSheet("""
                QPushButton {
                    background: #3498db;
                    color: white;
                    border: none;
                    padding: 5px 10px;
                    border-radius: 3px;
                    margin: 0 2px;
                }
            """)
            delete_btn.setStyleSheet("""
                QPushButton {
                    background: #e74c3c;
                    color: white;
                    border: none;
                    padding: 5px 10px;
                    border-radius: 3px;
                    margin: 0 2px;
                }
            """)

            admin_btn.setProperty('name', name)
            delete_btn.setProperty('name', name)
            class_layout.addWidget(label)
            class_layout.addStretch()
            class_layout.addWidget(admin_btn)
            class_layout.addWidget(delete_btn)
            admin_btn.clicked.connect(self.admin_class_btn_clicked)
            delete_btn.clicked.connect(self.delete_class_btn_clicked)
            show_layout.addLayout(class_layout)

        add_submit.clicked.connect(self.add_class)

    # 用户身份切换
    def update_account_placeholder(self, first=False):
        self.clear_layout(self.users_layout)
        add_layout = QHBoxLayout()
        input_layout = QVBoxLayout()
        self.users_layout.addLayout(add_layout)
        add_layout.addLayout(input_layout)

        # 美化输入区域
        input_frame = QFrame()
        input_frame.setStyleSheet("background: white; border-radius: 8px; border: 1px solid #ddd; padding: 15px;")
        input_layout_wrapper = QVBoxLayout(input_frame)
        add_layout.addWidget(input_frame)

        if self.student_radio.isChecked() or first == True:
            sf = 'student'
            self.input_student_name = QLineEdit()
            self.input_student_name.setPlaceholderText('学生姓名')
            self.input_student_name.setStyleSheet(
                "padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 10px;")
            input_layout_wrapper.addWidget(self.input_student_name)
            self.input_student_sno = QLineEdit()
            self.input_student_sno.setPlaceholderText('学生学号')
            self.input_student_sno.setStyleSheet("padding: 8px; border: 1px solid #ddd; border-radius: 4px;")
            input_layout_wrapper.addWidget(self.input_student_sno)
            submit = QPushButton('添加')
            submit.setStyleSheet("""
                QPushButton {
                    background: #2ecc71;
                    color: white;
                    border: none;
                    padding: 8px 15px;
                    border-radius: 4px;
                    margin-top: 10px;
                }
                QPushButton:hover {
                    background: #27ae60;
                }
            """)
            input_layout_wrapper.addWidget(submit)
            submit.setProperty('sf', 'student')
            submit.clicked.connect(self.add_user)
        else:
            self.input_teacher_name = QLineEdit()
            self.input_teacher_name.setPlaceholderText('教师姓名')
            self.input_teacher_name.setStyleSheet(
                "padding: 8px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 10px;")
            input_layout_wrapper.addWidget(self.input_teacher_name)
            self.input_teacher_sno = QLineEdit()
            self.input_teacher_sno.setPlaceholderText('教师学号')
            self.input_teacher_sno.setStyleSheet("padding: 8px; border: 1px solid #ddd; border-radius: 4px;")
            input_layout_wrapper.addWidget(self.input_teacher_sno)
            submit = QPushButton('添加')
            submit.setStyleSheet("""
                QPushButton {
                    background: #2ecc71;
                    color: white;
                    border: none;
                    padding: 8px 15px;
                    border-radius: 4px;
                    margin-top: 10px;
                }
                QPushButton:hover {
                    background: #27ae60;
                }
            """)
            input_layout_wrapper.addWidget(submit)
            submit.setProperty('sf', 'teacher')
            submit.clicked.connect(self.add_user)
            sf = 'teacher'
        par = {
            'sf': sf
        }
        response = requests.get('http://127.0.0.1:8000/admin/get_users', params=par).json()
        show_user_layout = QVBoxLayout()
        self.users_layout.addLayout(show_user_layout)

        # 美化用户列表区域
        list_frame = self.create_scroll(show_user_layout)
        list_frame.setStyleSheet("background: white; border-radius: 8px; border: 1px solid #ddd; padding: 15px;")
        list_layout = QVBoxLayout(list_frame)

        users = response.get('msg')
        for user in users:
            user_layout = QHBoxLayout()
            name = user.get('name')
            num = user.get('num')
            text = f'{num}--{name}'
            label = QLabel(text)
            label.setStyleSheet("padding: 8px; color: #2c3e50;")
            user_layout.addWidget(label)
            user_layout.addStretch()
            admin_sub = QPushButton('管理')
            delete_btn = QPushButton('删除')

            # 美化按钮
            admin_sub.setStyleSheet("""
                QPushButton {
                    background: #3498db;
                    color: white;
                    border: none;
                    padding: 5px 10px;
                    border-radius: 3px;
                    margin: 0 2px;
                }
            """)
            delete_btn.setStyleSheet("""
                QPushButton {
                    background: #e74c3c;
                    color: white;
                    border: none;
                    padding: 5px 10px;
                    border-radius: 3px;
                    margin: 0 2px;
                }
            """)

            admin_sub.setProperty('num', num)
            delete_btn.setProperty('num', num)
            user_layout.addWidget(admin_sub)
            user_layout.addWidget(delete_btn)
            list_layout.addLayout(user_layout)
            admin_sub.clicked.connect(self.admin_user_btn_clicked)
            delete_btn.clicked.connect(self.delete_user_btn_clicked)

    # 以下所有方法保持原有逻辑完全不变
    def add_user(self):
        sf = self.sender().property('sf')
        if sf == 'student':
            name = self.input_student_name.text()
            num = self.input_student_sno.text()
            print(bool(re.fullmatch(r'^\d{10}$', num)))
            if name == '' or not (bool(re.fullmatch(r'^\d{11}$', num))):
                QMessageBox.critical(None, '错误', '输入不规划')
                self.input_student_name.clear()
                self.input_student_sno.clear()
                return
            else:
                self.input_student_name.clear()
                self.input_student_sno.clear()
        else:
            name = self.input_teacher_name.text()
            num = self.input_teacher_sno.text()
            if name == '' or not (bool(re.fullmatch(r'^\d{11}$', num))):
                QMessageBox.critical(None, '错误', '输入不规划')
                self.input_teacher_name.clear()
                self.input_teacher_sno.clear()
                return
            else:
                self.input_teacher_name.clear()
                self.input_teacher_sno.clear()
        par = {
            'name': name,
            'num': num,
            'sf': sf
        }
        response = requests.post('http://127.0.0.1:8000/admin/add_user', json=par).json()
        if response.get('code') == 200:
            text = f'姓名:{name},账号:{num}--{sf}'
            QMessageBox.information(None, '添加成功', text)
        else:
            text = response.get('msg')
            QMessageBox.information(None, '错误', text)

    def admin_user_btn_clicked(self):
        self.clear_layout(self.x_layout)
        num = self.sender().property('num')
        par = {
            'num': num,
        }
        response = requests.get('http://127.0.0.1:8000/admin/get_users', params=par).json()
        user = response.get('msg')[0]
        id = user.get('id')
        name = user.get('name')
        num = user.get('num')
        sf = user.get('sf')
        if sf == 'teacher':
            par = {
                'num': num,
            }
            response = requests.get('http://127.0.0.1:8000/users/get_teacher', params=par).json()
            if response.get('code') == 200:
                teacher = response.get('msg')
                print(teacher)
            else:
                msg = response.get('msg')
                label = QLabel(msg)
                self.x_layout.addWidget(label)
        else:
            par = {
                'sno': num,
            }
            response = requests.get('http://127.0.0.1:8000/users/get_student', params=par).json()

            if response.get('code') == 200:
                student = response.get('msg')
                name=student.get('name')
                sno=student.get('sno')
                pwd=student.get('pwd')
                email=student.get('email')
                avatar=base64.b64decode(student.get('avatar_blob'))
                cla_id_id=student.get('cla_id_id')
                img_label = QLabel()
                img = QPixmap()
                img.loadFromData(avatar)
                img = img.scaled(120, 120, Qt.KeepAspectRatio)
                img_label.setPixmap(img)
                img_label.setAlignment(Qt.AlignCenter)
                left_layout=QVBoxLayout()
                self.x_layout.addLayout(left_layout)
                left_layout.addWidget(img_label)
                text=f'姓名:{name}'
                name_label=QLabel(text)
                left_layout.addWidget(name_label)
                text=f'学号:{sno}'
                sno_label=QLabel(text)
                left_layout.addWidget(sno_label)
                text=f'邮箱:{email}'
                email_label=QLabel(text)
                left_layout.addWidget(email_label)
                text=f'班级{cla_id_id}'



            else:
                msg = response.get('msg')
                label = QLabel(msg)
                self.x_layout.addWidget(label)

    def delete_user_btn_clicked(self):
        pass

    def add_class(self):
        name = self.input_class.text()
        pattern = r'^[\u4e00-\u9fa5]+\d{4}$'
        if re.match(pattern, name):
            par = {
                'name': name,
            }
            response = requests.post('http://127.0.0.1:8000/admin/add_class', params=par).json()
            if response.get('code') != 200:
                QMessageBox.critical(None, '错误', '该班级已添加')
            else:
                QMessageBox.information(None, '提示', '添加成功')
        else:
            QMessageBox.critical(None, '错误', '请输入正确的格式')

    def admin_class_btn_clicked(self):
        pass

    def delete_class_btn_clicked(self):
        name = self.sender().property('name')
        print(name)

    def add_course(self):
        name = self.input_course.text()
        if name != '':
            par = {
                'name': name,
            }
            response = requests.post('http://127.0.0.1:8000/admin/add_course', params=par).json()
            if response.get('code') != 200:
                QMessageBox.critical(None, '错误', '该课程已添加')
            else:
                QMessageBox.information(None, '提示', '添加成功')
        else:
            QMessageBox.critical(None, '错误', '请输入正确的格式')

    def admin_course_btn_clicked(self):
        pass

    def delete_course_btn_clicked(self):
        name = self.sender().property('name')
        print(name)

    def exit(self):
        if self.parent:
            self.parent.show()
        self.close()